package com.example.work01.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.work01.entity.User;
import com.example.work01.exception.PasswordErrorException;
import com.example.work01.exception.UsernameNotExistException;
import com.example.work01.service.UserService;
import com.example.work01.vo.AjaxResult;
import com.example.work01.vo.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 用户表 前端控制器
 *
 * @author myb
 * @since 2023-10-01
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {

    private final UserService userService;

    /**
     * 登录
     * @param loginVO
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody @Valid LoginVO loginVO) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, loginVO.getUsername());
        User queryUser = userService.getOne(wrapper);
        if (queryUser == null) {
            throw new UsernameNotExistException("该用户名不存在");
        }
        if (StringUtils.isEmpty(queryUser.getUsername()) || !queryUser.getPassword().equals(loginVO.getPassword())) {
            throw new PasswordErrorException("密码错误");
        }
        return AjaxResult.success(queryUser);
    }
}
